package com.cs342.g4.memaps;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.concurrent.ExecutionException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import basicClasses.Friend;
import basicClasses.Friends;
import basicClasses.LoginObject;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import asyncTasks.ApproveRequest;
import asyncTasks.DenyRequest;
import asyncTasks.GetFriends;

public class ViewFriendReqsts extends Activity {

	public static ListView listRequests;
	private ArrayList<String> requests = new ArrayList<String>();
	private ArrayAdapter<String> listRequestsAdapter;
	private String curUser;
	private String curPass;
	SharedPreferences mPrefs;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ActionBar ab = getActionBar();
		ab.setDisplayShowTitleEnabled(false);
		setContentView(R.layout.activity_view_friend_reqsts);

		Context mContext = this.getApplicationContext();
		mPrefs = mContext.getSharedPreferences("myPrefs", MODE_PRIVATE);

		curUser = mPrefs.getString("username", "");
		curPass = mPrefs.getString("password", "");
		LoginObject lo = new LoginObject(curUser, curPass);

		populateRequestsTask popTask = new populateRequestsTask();
		popTask.execute(lo);

	}

	public class populateRequestsTask extends
			AsyncTask<LoginObject, Void, ArrayList<String>> {
		ArrayList<String> requests = new ArrayList<String>();

		@Override
		protected ArrayList<String> doInBackground(LoginObject... params) {

			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(
					"http://softeng.cs.uwosh.edu/students/cs342g4/get_requests.php");
			String resp = "";
			try {
				// Convert the login object to XML
				XStream xstream = new XStream(new DomDriver("UTF-8"));
				xstream.alias("Login", LoginObject.class);
				String xml = xstream.toXML(params[0]);
				StringEntity se = new StringEntity(xml, HTTP.UTF_8);
				se.setContentType("text/xml");
				httppost.setEntity(se);
				HttpResponse httpresponse = httpclient.execute(httppost);
				HttpEntity resEntity = httpresponse.getEntity();
				resp = EntityUtils.toString(resEntity);
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			System.out.println(resp);
			System.out.println("sldkjsldfjksljfdlsjdflsjdflsjfdl");
			if (resp.equalsIgnoreCase("FALSE")) {
				return requests;
			} else {
				XStream xStream = new XStream();
				xStream.processAnnotations(new Class[] { Friends.class,
						Friend.class });
				Friends comments = (Friends) xStream.fromXML(resp);
				ArrayList<Friend> arr = comments.getArray();
				for (Friend x : arr) {
					requests.add(x.friendName);
				}
				return requests;
			}
		}

		@Override
		public void onPostExecute(ArrayList<String> requestss) {

			listRequests = (ListView) findViewById(R.id.requestsList);
			listRequestsAdapter = new ArrayAdapter<String>(
					ViewFriendReqsts.this, android.R.layout.simple_list_item_1,
					requestss);
			listRequests.setAdapter(listRequestsAdapter);

			listRequests.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					String rFrom = ((TextView)view).getText().toString();
					// popup to approve or deny request
					newRequest(view, rFrom);
				}
			});
		}
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	public void newRequest(View v, final String rFrom) {
		LayoutInflater inflater = (LayoutInflater) ViewFriendReqsts.this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.popup_friendsreqst, null, false);
		final PopupWindow popup = new PopupWindow(view,300,130,true);
		Button accept = (Button) view.findViewById(R.id.accept);
		Button deny = (Button) view.findViewById(R.id.deny);
		TextView fromR = (TextView) view.findViewById(R.id.requestFrom);
		fromR.setText(rFrom);
		popup.showAtLocation(v, Gravity.CENTER, 10, 10);
		popup.setFocusable(true);

		accept.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				LoginObject name = new LoginObject(rFrom,mPrefs.getString("username",""));
				ApproveRequest req = new ApproveRequest();
				try {
					req.execute(name).get();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (ExecutionException e) {
					e.printStackTrace();
				}
				popup.dismiss();
				LoginObject lo = new LoginObject(curUser, curPass);
				populateRequestsTask popTask = new populateRequestsTask();
				popTask.execute(lo);

			}
		});

		deny.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				LoginObject name = new LoginObject(rFrom,mPrefs.getString("username",""));
				DenyRequest req = new DenyRequest();
				try {
					req.execute(name).get();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (ExecutionException e) {
					e.printStackTrace();
				}
				popup.dismiss();
				LoginObject lo = new LoginObject(curUser, curPass);
				populateRequestsTask popTask = new populateRequestsTask();
				popTask.execute(lo);

			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.menu_items, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_favorites:
			Intent favs = new Intent(ViewFriendReqsts.this, FavoritePlacesActivity.class);
			startActivity(favs);
			return true;
		case R.id.menu_backToMap:
			Intent backToMap = new Intent(ViewFriendReqsts.this,
					MainActivity.class);
			startActivity(backToMap);
			finish();
			return true;
		case R.id.menu_viewFriends:
			Intent vFriends = new Intent(ViewFriendReqsts.this,
					ViewFriends.class);
			startActivity(vFriends);
			finish();
			return true;
		case R.id.menu_logout:
			SharedPreferences.Editor edit = mPrefs.edit();
			edit.putString("username", "");
			edit.putString("password", "");
			edit.commit();

			Intent loginAct = new Intent(ViewFriendReqsts.this,
					LoginActivity.class);
			startActivity(loginAct);
			finish();
			return true;
		}
		return false;
	}

	public boolean onPrepareOptionsMenu(Menu menu) {
		MenuItem mapType = menu.findItem(R.id.menu_setMapType);
		mapType.setVisible(false);
		return true;
	}
	
	@Override
	protected void onResume() {
		super.onResume();

		curUser = mPrefs.getString("username", "");
		curPass = mPrefs.getString("password", "");
		LoginObject lo = new LoginObject(curUser,curPass);
		
		populateRequestsTask popTask = new populateRequestsTask();
		popTask.execute(lo);
	}
}
